var windowW;
var windowH;
var examObj = null;
var peoObj = null;
var pageNum = 1;
var pageSize = 10;
var examCode = "1";
var provinceCode = "";
var minDate = "2000";
var maxDate = "2019";
var searchValue = "";
var initStatus = true;

function init(){
    getAjax("/sjgl/sentence/getDict?type=exam", function(data){
        examObj = data;
        var html1 = '';
        for(var i=0; i < data.length; i++){
            var name = data[i].name;
            var code = data[i].code;
            html1 +=  '<option value="'+code+'">'+name+'</option>';
        }
        $("#fenleiSelect").html(html1);
    }, function(e){
        console.log(e);
    });

    getAjax("/sjgl/sentence/getDict?type=province", function(data){
        peoObj = data;
        var html = '<option value="" selected="">全部</option>';
        for(var i = 0; i < data.length; i++){
            var code = data[i].code;
            var name = data[i].name;
            var sel = "";
            if(i == 0){
                sel = "selected";
            }
            html += '<option value="'+code+'" class="'+sel+'" >'+name+'</option>';
        }
        $('#proSelect').html(html);
        // getData("1" , "10", function(data){
        //     renderData(data);
        // });
        renderData();
    }, function(e){
        console.log(e);
        getData("1" , "10", function(data){
            renderData(data);
        });
    });
}

function renderData(){
    layui.use(['table', 'laydate', 'laypage', 'form'], function(){
        var table = layui.table;
        var laydate = layui.laydate;
        var laypage = layui.laypage;
        var form = layui.form;
        var width = windowW;
        var height = windowH - 100;

        form.on('select(test1)', function(data){
            console.log(data);
            examCode = data.value;
        });

        form.on('select(test2)', function(data){
            console.log(data);
            provinceCode = data.value;
        });

        laydate.render({
            elem: '#date1'
            ,type: 'year'
            ,max: '2030'
            ,btns: ['confirm']
            ,value: '2000 - 2019'
            ,trigger: 'click'
            // ,theme: '#2c72ec'
            ,range: true
            ,done: function(value, date, endDate){
                minDate = date.year;
                maxDate = endDate.year;
            }
        });

        var table = layui.table;

        var width = windowW;
        var height = windowH - 100;
        table.render({
            elem: '#test'
            , loading: true
            ,url : '../../paper/getList'
            // , data: data
            ,page : true
            ,request:{
                pageName:"pageNum"
                ,limitName:"pageSize"
            }
            ,where:{
                name : searchValue,
                subjects : '英语',
                maxYear : maxDate,
                minYear : minDate,
                province : provinceCode,
                exam : examCode
            }
            ,parseData: function(res) { //res 即为原始返回的数据
                return {
                    "code": 0, //解析接口状态
                    "msg": "", //解析提示文本
                    "count": res.totalElements, //解析数据长度
                    "data": res.content //解析数据列表
                };
            }
            ,limits:[10,15,20,50,100]
            , cols: [[ //表头
                //fixed: 'left'
                {type: 'checkbox', fixed: 'left'}
                , {
                    field: 'exam', title: '分类', width: 80, sort: true,
                    templet: function (d) {
                        if (d.exam == '1') {
                            return '中考'
                        } else if (d.exam == '2') {
                            return '高考'
                        } else {
                            return '小升初'
                        }
                    }
                }
                , {
                    field: 'province', title: '省份', width: 80, sort: true,
                    templet: function (d) {
                        return getText(d.province, peoObj);
                    }
                }
                , {field: 'name', title: '试卷名称', sort: true, width: (width - 80 - 80 - 180 - 80)}
                , {fixed: 'right', title: '操作', width: 180, align: 'center', toolbar: '#barDemo'}
            ]]
        });

        //监听表格复选框选择
        table.on('checkbox(demo)', function(obj){
            console.log(obj)
        });
        //监听工具条
        table.on('tool(demo)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                layer.confirm('真的删除行么', function(index){
                    var str = obj.data.id;
                    del(str);
                    layer.close(index);
                });
            }
        });

        var $ = layui.$, active = {
            getCheckData: function(){ //获取选中数据
                var checkStatus = table.checkStatus('test')
                    ,data = checkStatus.data;
                // layer.alert(JSON.stringify(data));
                var str = "";
                for(var i = 0; i < data.length; i++){
                    str += data[i].id + ",";
                }
                if(str.length > 1){
                    str = str.substring(0,str.length -1);
                }
                del(str);
            },
            reload : function(){
                table.reload('test', {
                    where: {
                        name: searchValue,
                        subjects: '英语',
                        maxYear: maxDate,
                        minYear: minDate,
                        province: provinceCode,
                        exam: examCode
                    }
                    ,page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            }
        };

        $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        $('#searchBtn').on('click', function(){
            searchValue = $("searchValue").val() == null ? "" : $("searchValue").val();
            var type = $(this).data('type');
            pageNum = 1;
            pageSize = 10;
            active[type] ? active[type].call(this) : '';
        });
    });
}


function reloadTable(){
    layui.use(['table', 'laydate', 'laypage'], function() {
        var table = layui.table;

        table.reload('test', {
            url: '../../paper/getList'
            , request: {
                pageName: "pageNum"
                , limitName: "pageSize"
            }
            , where: {
                name: searchValue,
                subjects: '英语',
                maxYear: maxDate,
                minYear: minDate,
                province: provinceCode,
                exam: examCode
            }
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": 0, //解析接口状态
                    "msg": "", //解析提示文本
                    "count": res.totalElements, //解析数据长度
                    "data": res.content //解析数据列表
                };
            }
            ,page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    });
}

function del(str){
    // getAjax("../../paper/delPapers?ids=" + str, function(a){
    //     reloadTable();
    // }, function(e){
    //     console.log(e.statusText);
    //     if(e.statusText == "OK" || e.responseText == "删除成功"){
    //         alert(e.responseText);
    //         reloadTable();
    //     }
    // });

    $.ajax({
        url: "../../paper/delPapers?ids=" + str,
        type: "GET",
        dataType: "text",
        error: function (e) {
            console.log(e.statusText);
        },
        success: function (data) {
            reloadTable();
        }
    });
}

function getAjax(url, callbackFun, errorFun) {
    $.ajax({
        url: url,
        type: "GET",
        dataType: "json",
        error: function (e) {
            errorFun(e);
        },
        success: function (data) {
            callbackFun(data);
        }
    });
}

function getText(value, data){
    for(var i = 0; i < data.length; i++){
        if(data[i]["code"] == value){
            return data[i]["name"];
            break;
        }
    }
}

$(document).ready(function(){
    if(initStatus){
        initStatus = false;
        windowW = $("body").width();
        windowH = $(window).height();
        init();
    }
});